<template>
  <!-- 记录设备归返管理[查看/新增归还] -->
  <base-breadcrumb>
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
                  id="base-breadcrumb" style="position: relative"
                  :rules="queryParams.editModel != 0 ? rules : {}">
      <a-spin :spinning="loading">
        <a-card>
          <title-name title="基础信息" />
          <custom-form ref="form" :rules="rules" :editModel="''" :form="form" :form-list="formList"
                       :formComponents="$refs" @selectOrg="selectOrg">
          </custom-form>
        </a-card>
        <a-card>
          <title-name title="计量设备归还清单" />
          <searchData ref="searchData" v-if="queryParams.editModel == 0" :search-data="searchArr"
                      @search="search" @reset="search" />
          <a-card>
            <b-table ref="table" bordered rowKey="id" :isShowTotal="false" :isShowCountBar="false"
                     :showPage="false" :columns="columns" :dataSource="mdInfoReturnInventoryBOs"
                     :scroll="{ x: 1600 }">
              <a-button slot="prefix" type="primary" icon="plus" v-if="queryParams.editModel != 0"
                        @click="addReturnEquipment">新增归还计量设备</a-button>
              <template slot="actions" slot-scope="text, record,index">
                <MoreButton>
                  <a @click="handleDelete(index)">删除</a>
                </MoreButton>
              </template>
            </b-table>
          </a-card>
        </a-card>
      </a-spin>
    </a-form-model>
    <!-- 页脚操作栏 -->
    <div class="btn_box page-btn-right-top">
      <div v-if="queryParams.editModel != 0">
        <a-button :loading="loading" type="primary" class="button_right" @click="handleSubmit">提交
        </a-button>
      </div>
      <a-button type="primary" @click="handleActiveClose">关闭</a-button>
    </div>
    <equipment-selected v-if="equipmentSelectedVisible" :visible.sync="equipmentSelectedVisible"
                        :form="form" @handelShow="handelShow" @handleClick="handleModalClick" />
  </base-breadcrumb>
</template>

<script>
import api from '@/api/quality/recordDeviceReturnManagement' // api
import dataFilter from '@/views/quality/equipmentManagement/constant/dataFilter'
import { equipmentStatusArr, returnStatusArr } from '@/views/quality/equipmentManagement/constant/dictionary'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import equipmentSelected from './components/equipmentSelected.vue'
export default {
  name: "recordDeviceReturnManagementInfo",
  extends: new BaseEditPage(),
  components: {
    equipmentSelected,
  },
  data() {
    const columns = [
      {
        title: '序号',
        width: 80,
        dataIndex: 'number',
        showPage: [0, 1, 2, 3],
        customRender() {
          return arguments[2] + 1
        }
      },
      {
        title: '设备名称',
        dataIndex: 'mdName',
        ellipsis: true,
      },
      {
        title: '设备编号',
        dataIndex: 'mdCode',
        ellipsis: true,
      },
      {
        title: '规格型号',
        dataIndex: 'specificationModel',
        ellipsis: true,
        width: 200,
      },
      {
        title: '进场时间',
        dataIndex: 'inProjectTime',
        width: 160,
      },
      {
        title: '使用单位',
        dataIndex: 'projectName',
        ellipsis: true,
      },
      {
        title: '设备状态',
        dataIndex: 'mdStatus',
        width: 160,
        customRender: (text) => {
          return dataFilter(equipmentStatusArr, ['1']).find(item => item.value === text)?.label
        }
      },
      {
        title: '归还状态',
        dataIndex: 'returnStatus',
        width: 160,
        customRender(text, record, index) {
          if (text) {
            return returnStatusArr.find((item) => item.value == text).label
          } else {
            return text;
          }
        }
      },
      {
        title: '归还时间',
        dataIndex: 'returnTime',
        width: 160,
      },
      {
        title: '归还情况说明',
        dataIndex: 'remarks',
      },
      {
        title: '操作',
        dataIndex: 'actions',
        width: 180,
        fixed: 'right',
        align: 'center',
        scopedSlots: { customRender: 'actions' }
      }
    ];
    let [showFieldArr, columnsData, fixedDataColumn] = [[], [], ['number', 'mdName', 'mdCode', 'specificationModel', 'actualInTime', 'projectName']];
    if (this.$route.query.editModel == 1) {
      showFieldArr = [...fixedDataColumn, ...['mdStatus', 'actions']]
    } else {
      showFieldArr = [...fixedDataColumn, ...['returnStatus', 'returnTime', 'remarks']]
    }
    this.$clone(columns).forEach((item) => {
      if (showFieldArr.includes(item.dataIndex)) {
        columnsData.push(item);
      }
    });
    return {
      loading: false,
      api,//api
      queryParams: this.$route.query, //页面路由参数
      userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info')),
      searchParams: {},
      // 表单
      form: {},
      mdInfoReturnInventoryBOs: [],
      rules: {
        projectId: [{ required: true, message: '请选择归还单位', trigger: 'change' }],
        remarks: [{ required: true, message: '请输入归还说明', trigger: 'change' }],
      },
      searchArr: [
        {
          name: '设备编号',
          type: 'input',
          value: 'mdCode',
        },
        {
          name: '设备名称',
          type: 'input',
          value: 'mdName',
        },
      ],
      columns: columnsData,
      equipmentSelectedVisible: false,//归还设备弹窗状态
    }
  },
  computed: {
    formList() {
      let formList = [
        {
          label: '归还单位',
          type: 'orgTree',
          keyName: 'projectId',
          isAutoSelectFirst: this.queryParams.editModel == 1 ? true : false,
          checkStrictly: true,
        },
        {
          label: '归还个数',
          keyName: 'returnNum',
          type: 'BaseInput',
        },
        {
          label: '填报人',
          keyName: 'informant',
          type: 'BaseInput',
        },
        {
          keyName: 'fillingTime',
          type: 'a-date-picker',
          placeholder: '请选择填报时间',
          label: '填报时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          label: '最终归还个数',
          keyName: 'confirmReturnNum',
          type: 'BaseInput',
        },
        {
          label: '创建人',
          keyName: 'creator',
          type: 'BaseInput',
          disabled: true,
        },
        {
          keyName: 'createTime',
          type: 'a-date-picker',
          placeholder: '请选择创建时间',
          label: '创建时间',
          disabled: true,
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'remarks',
          label: '归还说明',
          type: 'BaseTextarea',
          span: 16,
        }
      ];
      let [showFieldArr, formData] = [[], []];
      if (this.queryParams.editModel == 1) {
        showFieldArr = ['projectId', 'creator', 'createTime', 'remarks'];
      } else {
        showFieldArr = ['projectId', 'returnNum', 'informant', 'fillingTime', 'confirmReturnNum', 'remarks']
      }
      this.$clone(formList).forEach((item) => {
        if (this.queryParams.editModel == 0) {
          this.$set(item, 'disabled', true)
        }
        if (showFieldArr.includes(item.keyName)) {
          formData.push(item);
        }
      });
      return formData;
    }
  },
  mounted() {
    if (this.queryParams.editModel == 1) {
      this.form.createTime = this.$dateFormat(new Date(), 'D');
      this.form.creatorId = this.userInfo.id;
      this.form.creator = this.userInfo.name;
    } else {
      this.getFormDetailData();
      this.getReturnList();
    }
  },
  methods: {
    /**
     * @description: 选中归还单位需要执行的操作
     */
    selectOrg() {
      if (this.queryParams.editModel == 1) {
        this.mdInfoReturnInventoryBOs = [];
      }
    },
    /**
     * @description: 当关闭弹窗时，同步equipmentSelectedVisible的值
     * @param {Boolean} e true:显示 false:隐藏
     */
    handelShow(e) {
      this.equipmentSelectedVisible = e
    },
    /**
     * @description: 打开选择设备的弹出框
     */
    addReturnEquipment() {
      if (!this.form.projectId || this.form.projectId == '') {
        this.$message.warning("请选择归还单位")
        return
      }
      this.equipmentSelectedVisible = true
    },
    /**
     * @description: 获取所选中的数据
     * @param {Object} data 选中的数据
     */
    handleModalClick(data) {
      data.rows.forEach(rowItem => {
        if (
          !this.mdInfoReturnInventoryBOs.find(item => {
            return rowItem.id === item.id
          })
        ) {
          this.mdInfoReturnInventoryBOs.push(rowItem)
        }
      })
    },
    /**
     * @description: 操作删除
     * @param {Number} index 删除数据的下标
     */
    handleDelete(index) {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除当前归还项？',
        onOk: () => {
          this.mdInfoReturnInventoryBOs.splice(index, 1)
        }
      })
    },
    /**
     * @description:获取表单详情数据
     */
    async getFormDetailData() {
      let res = await this.api.getDetail({ id: this.queryParams.id });
      if (res.code === '0') {
        let { projectId, projectName, returnNum, creator, createTime, confirmReturnNum, remarks } = res.data;
        this.form = {
          projectId,
          projectName,
          returnNum,
          informant: creator,
          fillingTime: createTime,
          confirmReturnNum,
          remarks
        };
      }
    },
    /**
     * @description:获取归还清单列表
     */
    async getReturnList() {
      const requestParameters = { ...this.searchParams, ...{ returnId: this.queryParams.id } }
      let res = await this.api.queryMdInfoReturnInventoryList(requestParameters);
      if (res.code === '0') {
        let arr = [];
        if (res.data && res.data.length) {
          res.data.forEach((item) => {
            arr.push({
              id: item.id,
              mdName: item.mdName,
              mdCode: item.mdCode,
              specificationModel: item.specificationModel,
              inProjectTime: item.actualInTime,
              projectId: item.projectId,
              projectName: item.projectName,
              returnStatus: item.returnStatus,
              returnTime: item.returnTime,
              remarks: item.remarks
            })
          })
        }
        this.mdInfoReturnInventoryBOs = arr;
      }
    },
    /**
     * @description:提交表单
     */
    handleSubmit() {
      let that = this;
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          // 校验归还计量设备项表单
          if (that.mdInfoReturnInventoryBOs.length == 0) {
            that.$message.warning('归还设备项不能为空')
            return
          }
          that.$confirm({
            title: '温馨提示',
            content: '是否确定提交？',
            onOk: () => {
              let params = { ...that.form, ...{ mdInfoReturnInventoryBOs: [] } };
              that.mdInfoReturnInventoryBOs.forEach((item) => {
                if (item.inProjectTime) item.inProjectTime = item.inProjectTime + ' 00:00:00'
                params.mdInfoReturnInventoryBOs.push({
                  mdProjectId: item.id,//项目设备台账id
                  mdOwnId: item.mdOwnId,//自有设备id
                  mdName: item.mdName,
                  mdCode: item.mdCode,
                  mdModelId: item.mdModelId,
                  specificationModel: item.specificationModel,
                  actualInTime: item.inProjectTime,
                  projectName: item.projectName,
                  projectId: item.projectId,
                  mdStatus: item.mdStatus,
                })
              })
              if (params.createTime) params.createTime = params.createTime + ' 00:00:00'
              that.loading = true
              that.api.create(params).then((res) => {
                if (res.code === '0') {
                  that.loading = false
                  that.$message.success('提交成功！')
                  that.$multiTab.close()
                }
              }).catch((err) => {
                that.loading = false
              })
            }
          })
        } else {
          that.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    /**
     * @description:查询
     */
    search(val) {
      this.searchParams = val || {}
      this.getReturnList();
    }
  }
}
</script>

<style>
</style>